<template>
  <el-upload
    class="avatar-uploader"
    :show-file-list="false"
    :http-request="upload"
    :before-upload="beforeAvatarUpload"
    action="#"
    :on-success="handleAvatarSuccess"
  >
    <img
      v-if="modelValue"
      :src="modelValue"
      class="avatar"
    />
    <el-icon
      v-else
      class="avatar-uploader-icon"
    >
      <i-ep-plus />
    </el-icon>
  </el-upload>
  <br>
  <el-progress
    v-if="isShowprogress"
    :percentage="percent"
    class="el-progress--line "
  />
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import COS from 'cos-js-sdk-v5'
import type { UploadProps } from 'element-plus'
const cos = new COS({
  SecretId: 'AKIDHSeeXGlDHFBxYyHUeopdFk5HO7ic6Yr1', // 身份识别ID
  SecretKey: '8zhyEJIB0hCfBg4c3KUgx6614675zk4L', // 身份秘钥
})
interface UploadImg {
  headers: Headers;
  withCredentials: boolean;
  file: File;
  data: Headers;
  method: string;
  filename: string;
  action: string;
}
const isShowprogress=ref(false)
const percent=ref(0)
defineProps<{
  modelValue: string,
}>()
const emit= defineEmits(['update:modelValue'])
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {}
const  upload=({ file } :UploadImg) =>{
  //console.log('file', file)
  // 执行上传操作
  isShowprogress.value=true
  cos.putObject({
    Bucket: 'wh82-1257017897', /* 存储桶 */
    Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
    Key: file.name, /* 文件名 */
    StorageClass: 'STANDARD', // 上传模式, 标准模式
    Body: file, // 上传文件对象
    onProgress: (progressData) => {
      console.log(JSON.stringify(progressData))
      percent.value=progressData.percent*100
    },
  }, (err, data) => {
    //console.log(err || data)
    //if(data.statusCode===200) imageUrl.value = `https:${ data.Location }`
    if(data.statusCode===200) emit('update:modelValue',`https:${ data.Location }`) 
    isShowprogress.value=false
  })
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
} .el-progress--line {

  margin-bottom: 15px;
  width: 220px;
}

</style>

<style>
.el-form-item__content{
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
